package main

import (
	"fmt"
	"go_web/src/controller"
	"go_web/src/middleware"
	"go_web/src/repositories"
	"go_web/src/services"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func LogMiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		middleware.LogMiddleWare(c)
	}
}

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		middleware.AuthMiddleware(c)
	}
}

func main() {

	// 1. 初始化数据库
	dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	// 2. 初始化各层（依赖注入）
	userRepo := repositories.NewUserRepository(db)
	userService := services.NewUserService(userRepo)
	userController := controller.NewUserController(userService)
	orderRepo := repositories.NewOrderRepository(db)
	orderService := services.NewOrderService(orderRepo, userRepo)
	orderController := controller.NewOrderController(orderService)

	// 3. 设置Gin路由
	r := gin.Default()

	//3.1 上传文件大小设置
	r.MaxMultipartMemory = 8 << 20 // 8 MiB,
	//3.2 中间件设置
	r.Use(LogMiddleWare())
	r.Use(AuthMiddleware())

	api := r.Group("/api/v1")
	{
		api.POST("/create", userController.CreateUser)
		api.POST("/update", userController.UpdateUser)
		api.GET("/GetUser", userController.GetUser)
		api.DELETE("/delete/:id", userController.DeleteUser)

	}

	order := r.Group("/api/order")
	{
		order.POST("/create", orderController.CreateOrder)
		order.GET("/get", orderController.GetOrder)
	}

	// 加载 HTML 模板（模板文件放在 templates/ 目录）
	r.LoadHTMLGlob("templates/*")
	// 或者加载特定文件 r.LoadHTMLFiles("templates/index.html", "templates/about.html")

	fmt.Println("Hello Go Web Demo")
	r.Run(":8080") // 监听 0.0.0.0:8080
}
